import path from 'path'

let http = {};

http.baseUrl = ""
http.defaultHeader = {}

var urlEncode = function (param, key, encode) {
  if(param==null) return '';
  var paramStr = '';
  var t = typeof (param);
  if (t == 'string' || t == 'number' || t == 'boolean') {
    paramStr += '&' + key + '=' + ((encode==null||encode) ? encodeURIComponent(param) : param);
  } else {
    for (var i in param) {
      var k = key == null ? i : key + (param instanceof Array ? '[' + i + ']' : '.' + i);
      paramStr += urlEncode(param[i], k, encode);
    }
  }
  return paramStr;
};

http.request = function(url, data, config){
	config || (config = {})
	data || (data = {})
	config.header = Object.assign({"content-type": "application/json"}, this.defaultHeader, config.header)
	return new Promise((resolve, reject) => {
		url = this.baseUrl + url
		uni.request({
			url: url,
			data,
			...config,
			complete(res) {
				if(res.statusCode == 200){
					resolve(res)
				}else {
					reject(res)
				}
			}
		})
	})
}

http.get = function(url, data, config){
	if(!!data){
		url += '?' + urlEncode(data).slice(1)
	}
	config || (config = {})
	
	config.method = "GET";
	
	return this.request(url, {}, config)
}

http.post= function(url, data, config){
	config || (config = {})
	
	config.method = "POST";
	return this.request(url, data, config)
}

http.put= function(url, data, config){
	config || (config = {})
	
	config.method = "PUT";
	return this.request(url, data, config)
}

http.delete= function(url, data, config){
	config || (config = {})
	
	config.method = "DELETE";
	return this.request(url, data, config)
}

module.exports = http